package com.LC.Service.Impl;

import com.LC.Constant.RedisConstant;
import com.LC.DAO.SetMealDAO;
import com.LC.Entity.*;
import com.LC.Service.SetMealService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDAO setMealDAO;

    @Autowired
    private JedisPool jedisPool;

    /*@Autowired
    private FreeMarkerConfigurer FreeMarkerConfigurer;*/

    /*@Value("${out_put_path}")
    private String outPutPath;*/ //从属性文件中读取要生成的目录结构

    @Override
    public List<CheckGroup> findAllCheckGroup() {
        return setMealDAO.findAllCheckGroup();
    }

    @Override
    public PageResult showMeal(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //mybatis分页助手
        PageHelper.startPage(currentPage, pageSize);
        Page<SetMeal> setMealPage = setMealDAO.findSetMealByCondition(queryString);
        PageResult pageResult = new PageResult(setMealPage.getTotal(), setMealPage.getResult());
        return pageResult;
    }

    @Override
    public void addMeal(SetMeal setMeal, Integer[] checkGroupIds) {
        setMealDAO.addTot_setmeal(setMeal);
        //获取img名称并保存到Redis中，这里是实际存到数据库中的图片名
        String fileName = setMeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        Integer mealId = setMeal.getId();
        if (checkGroupIds == null || checkGroupIds.length == 0) {
            throw new RuntimeException();
        } else {
            for (Integer checkGroupId : checkGroupIds) {
                setMealDAO.addTot_setmeal_checkgroup(mealId, checkGroupId);
            }
        }
        //生成静态页面
        //generateMobileStaticHtml();
    }

    @Override
    public List<SetMeal> findAllMeal() {
        return setMealDAO.findAllSetMeal();
    }

    @Override
    public SetMeal findById(int id) {
        SetMeal setMealById = setMealDAO.findById(id);
        //根据套餐id查询包含的检查组
        List<CheckGroup> groupList = setMealDAO.findByMealId(id);
        //根据检查组id查询包含的检查项
        for (CheckGroup checkGroup : groupList) {
            List<CheckItem> byGroupId = setMealDAO.findByGroupId(checkGroup.getId());
            checkGroup.setCheckItems(byGroupId);
        }
        //封装
        setMealById.setCheckGroups(groupList);
        return setMealById;
    }

    /**
     * * 套餐数据饼形图所需数据
     *
     * @return
     */
    @Override
    public List<PieData> setMealReport() {
        //从订单表中查询出所有套餐ID
        List<Integer> mealIdFromOrderTable = setMealDAO.findMealIdFromOrderTable();
        //去除重复ID
        for (int i = 0; i < mealIdFromOrderTable.size(); i++) {
            for (int j = i + 1; j < mealIdFromOrderTable.size() - i - 2; j++) {
                if (mealIdFromOrderTable.get(i) == mealIdFromOrderTable.get(j)) {
                    mealIdFromOrderTable.remove(j);
                }
            }
        }
        List<PieData> list = new ArrayList();
        for (Integer mealId : mealIdFromOrderTable) {
            //从套餐表中查询套餐名，封装
            //根据套餐ID从订单表中查询出现次数，封装
            PieData pieData = new PieData(setMealDAO.findById(mealId).getName(), setMealDAO.mealCountFromOrderTable(mealId));
            list.add(pieData);
        }
        return list;
    }

    /**
     * 根据套餐id查询包含的检查项，返回它们的id
     *
     * @param mealId
     * @return
     */
    @Override
    public List<Integer> findCheckGroupIdsByMealId(int mealId) {
        List<CheckGroup> byMealId = setMealDAO.findByMealId(mealId);
        List<Integer> CheckGroupIdList = null;
        if (byMealId != null && byMealId.size() > 0) {
            CheckGroupIdList = new ArrayList<>();
            for (CheckGroup checkGroup : byMealId) {
                CheckGroupIdList.add(checkGroup.getId());
            }
        }
        return CheckGroupIdList;
    }

    /**
     * 更新套餐数据
     *
     * @param checkGroupIds
     * @param setMeal
     */
    @Override
    public void updateMealData(Integer[] checkGroupIds, SetMeal setMeal) {
        setMealDAO.updateMeal(setMeal);
        setMealDAO.deleteCheckGroupIdByMealId(setMeal.getId());
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            for (Integer checkGroupId : checkGroupIds) {
                setMealDAO.addTot_setmeal_checkgroup(setMeal.getId(), checkGroupId);
            }
        }
    }

    /**
     * 删除套餐
     *
     * @param mealId
     */
    @Override
    public void deleteMeal(int mealId) {
        try {
            setMealDAO.deleteCheckGroupIdByMealId(mealId);
            setMealDAO.delete(mealId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /**
     * 生成当前方法所需的静态页面
     */
    /*public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<SetMeal> allSetMeal = setMealDAO.findAllSetMeal();
        //需要生成套餐列表静态页面
        generateMobileSetMealListHtml(allSetMeal);
        //需要生成套餐详情静态页面
        generateMobileSetMealDetailListHtml(allSetMeal);
    }*/

    /**
     * 生成套餐列表页面
     *
     * @param list
     */
    /*public void generateMobileSetMealListHtml(List<SetMeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);
        generateHtml("Mobile_SetMeal.ftl", "M_SetMeal.html", map);
    }*/

    /**
     * 生成套餐详情页面
     *
     * @param list
     */
    /*public void generateMobileSetMealDetailListHtml(List<SetMeal> list) {
        for (SetMeal setMeal : list) {
            Map map = new HashMap();
            map.put("setmeal", findById(setMeal.getId()));
            generateHtml("Mobile_SetMealDetail.ftl", "setmeal_detail_" + setMeal.getId() + ".html", map);
        }
    }*/

    /**
     * 通用的  用于生成静态页面的方法
     *
     * @param templateName
     * @param htmlName
     * @param map
     */
    /*public void generateHtml(String templateName, String htmlName, Map map) {
        Writer out = null;
        //获得配置对象
        Configuration configuration = FreeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate(templateName);
            //构建输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
